import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class shiyan3_3 {
    private static DatagramSocket mSocket;
    //默认密钥
    public static final String key = "jkl;POIU1234++==";
    public static final byte[] rand = {1,2,3,4,5,6,7,8};

    public static void main(String[] args) {
        try {
            // 1.初始化DatagramSocket，指定端口号
            mSocket = new DatagramSocket(8000);
            // 2.创建用于接收消息的DatagramPacket，指定接收数据大小

            // 3.接收客户端消息
            while (true) {
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                mSocket.receive(receivePacket);// 在接收到信息之前，一直保持阻塞状态
		byte[] data = funcByteToStr(receiveData).getBytes();
		char[] password = key.toCharArray();
		PBEKeySpec pbks = new PBEKeySpec(password);
                System.out.println(receiveData);

		SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey k = kf.generateSecret(pbks);
		Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");
		PBEParameterSpec ps = new PBEParameterSpec(rand,1000);
		cp.init(Cipher.DECRYPT_MODE,k,ps);
		byte[] outda = cp.doFinal(data);

                System.out.println("客户端说:" + funcByteToStr(outda));
                String str=funcByteToStr(outda);
                if (str.equals("bye")){
                    mSocket.close();
                    return;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mSocket.close();// 关闭资源
        }
    }

    public static String funcByteToStr(byte[] buffer) {
        try {
            int length = 0;
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] == 0) {
                    length = i;
                    break;
                }
            }
            return new String(buffer,0,length);
        } catch (Exception e) {
            return "";
        }
    }


    static class HandleThread extends Thread {
        private DatagramPacket mPacket;
        private DatagramSocket mSocket;

        public HandleThread(DatagramPacket packet) {
            super();
            mPacket = packet;
        }

        @Override
        public void run() {
            try {
                mSocket = new DatagramSocket();
                mSocket.send(mPacket);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (mSocket != null) {
                    mSocket.close();// 关闭资源
                }
            }
        }
    }
}
